var source;//EventSource实例
var term;//xtermjs实例
var layer;
var userId;
$(function(){
	userId=getQueryVariable("userId");
	init();
	initEventSource();
	setData();
	initXtremJs();
	runFakeTerminal();
	setTimeout(function(){sendMsg("DQ==");},1000);
	console.log(userId);
});

function init(){//初始化
	if("EventSource" in window){//withCredentials用于支持跨域,并连同cookie也进行一起发送
		source =new EventSource("/xterm/push?userId="+userId,{withCredentials:true});
	}else{
		alter("您的浏览器不支持");
	}
	layui.use('layer',function(){
		layer=layui.layer;
	});	
}

$(window).on('unload',function(){
	closeWindow();
	setTimeout(function(){},1000);
});

$(window).on('beforeunload',function(){
	replaceWindow();
	setTimeout(function(){},1000);
});

function initXtremJs(){
	term = new Terminal({
		rendererType:"canvas",
        rows: 37,
        cursorBlink: true, // 光标闪烁
        convertEol: true, //启用时，光标将设置为下一行的开头
        disableStdin: false, //是否应禁用输入。
        scrollback: 800, //回滚
        tabStopWidth: 8, //制表宽度
        screenKeys: true
    });
	var fitAddon=new window.FitAddon.FitAddon();
	term.loadAddon(fitAddon);
    term.open(document.getElementById('terminal'));
    fitAddon.fit();
    term.write('Connecting...\r\n');
}
function runFakeTerminal() {
    if (term._initialized) {
        return;
    }
    term._initialized = true;
    term.write('Welcome to xterm.js');
    term.onData(function(data){
    	sendMsg(Base64.encode(data));
    });
}

function sendMsg(msg){
	$.ajax({
		type:"GET",
		url:"./send",
		data:{"message":msg,"userId":userId},
		success:function(data){
			if(data.code!=0){
				let msg=data.message;
				if(msg=="null"){
					msg="连接失败！";
				}
				layer.alert(msg,{icon:2},function(){
					window.location.href="./index";
				});
			}
		},
		error:function(data){
			console.log(data);
		}
	});
}

function initEventSource(){
	source.onopen=function(e){
		console.log("eventSource is open");
	}
	source.addEventListener("error",function(e){
		if(e.currentTarget.readyState==EventSource.CLOSED){
			console.log("连接关闭");
		}else{
			console.log(event.readyState);
		}
	},false);
}

function setData(){
	source.onmessage=function(e){
		let returnMessage=Base64.decode(e.data);
		term.write(returnMessage);
	}
}

function closeWindow(){//关闭浏览器的时候
	$.ajax({
		type:"GET",
		url:"./close",
		data:{"userId":userId},
		success:function(data){
			console.log(data);
		},
		error:function(data){
			console.log(data);
		}
	});
}
function replaceWindow(){
	$.ajax({
		type:"GET",
		url:"./replaceWindow",
		data:{"userId":userId},
		success:function(data){
			console.log(data);
		},
		error:function(data){
			console.log(data);
		}
	});
}
/**
 * 用于获取浏览器上的参数信息
 * 比如：http://127.0.0.1:8080/interface/user/getUser?userCode=1
 * 传入字符串 userCode 返回 1
 * 如果没有找到参数，则返回false 可以用if判断有没有返回值
 * */
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		let param=vars[i];
		let index=param.indexOf('=');
		var pair = param.substring(0,index);
		if (pair == variable) {
			return param.substring(index+1,param.length);
		}
	}
	return (false);
}